package edu.xidian.sei.mlcs
import java.util.Arrays

case class Location(val index: Array[Short]) extends Ordered[Location] {
  override val hashCode = buildHashCode

  def indexSum = index.sum

  def toFileIndex = index.mkString("-")

  override def toString: String = {
    Arrays.toString(index)
  }
  private def buildHashCode: Int = {
    var hashCode = 1
    var i = 0
    val a = index
    while (i < a.length) {
      hashCode = 31 * hashCode + a(i)
      i += 1
    }
    hashCode
  }

  override def equals(o: Any): Boolean = {
    val bl = o.asInstanceOf[Location]
    if (bl eq this) return true
    val b = bl.index
    val a = index
    var i = 0
    var equals = true
    while (i < a.length && equals) {
      if (a(i) != b(i)) {
        equals = false
      }
      i += 1
    }
    equals
  }
  override def compare(l: Location): Int = {
    var i = 0
    val a = index
    val b = l.index
    var less = 0
    var greate = 0
    var lessIndex = 0
    var oLessIndex = 0
    while (i < a.length) {
      if (a(i) < b(i)) {
        less += 1
        lessIndex += i
      } else if (a(i) > b(i)) {
        greate += 1
        oLessIndex += i
      }
      i += 1
    }
    if (less > greate) -1
    else if (less < greate) 1
    else lessIndex - oLessIndex
  }
}

object Location {
  def main(args: Array[String]): Unit = {
    val l1 = new Location(Array[Short](52, 67, 53, 56, 47))
    val l2 = new Location(Array[Short](41, 62, 47, 48, 44))
    val l3 = new Location(Array[Short](5, 3, 5, 1, 7))
    val ab = new Array[Location](3)
    ab(0) = l1
    ab(1) = l2
    ab(2) = l3
    val ac = ab.sorted
    for (a <- ac)
      println(a)
  }
}